package com.weic.easycache.task;

import java.sql.SQLException;

import android.content.Context;

import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.weic.easycache.framework.biz.IDbBiz;

public class DBTask extends AbsTask {
	private final Dao<?, ?> mDao;
	private final boolean mWritable;
	private final IDbBiz<?> mBiz;
	
	public DBTask(Context context, int id, Dao<?, ?> dao, boolean writable, IDbBiz<?> biz) {
		super(context, id, biz, false);
		mDao = dao;
		mWritable = writable;
		mBiz = biz;
	}

	@Override
	protected boolean doSomething() throws Exception {
		if(mWritable) {
			return write();
		}else {
			return read();
		}
	}

	private boolean read() throws SQLException {
		QueryBuilder<?, ?> queryBuilder = mDao.queryBuilder();
		mBiz.createQuery(mId, queryBuilder);
		CloseableIterator<?> iterator = null;
		String message = null;
		try {
			iterator = queryBuilder.iterator();
			message = mBiz.update(mId, iterator);
		} finally {
			if(iterator != null) try { iterator.close(); }catch(SQLException e) { e.printStackTrace(); }
		}
		if(message == null) {	//IDbBiz.RESULT_OK
			return true;
		}else {
			if(message.length() > 0) setMessage(null, null, message);	//IDbBiz.RESULT_FAILURE
			return false;
		}
	}
	
	private boolean write() throws SQLException {
		String message = null;
		try {
			message = mBiz.writeDB(mId, mDao);
		} finally {
			try { mDao.closeLastIterator(); }catch(SQLException e) { e.printStackTrace(); }
		}
		if(message == null) {	//IDbBiz.RESULT_OK
			return true;
		}else {
			if(message.length() > 0) setMessage(null, null, message);	//IDbBiz.RESULT_FAILURE
			return false;
		}
	}
}
